package com.yuchen.ishop.service.admin.goods.impl;

import com.yuchen.core.jdbc.BaseDao;
import com.yuchen.ishop.Gobals;
import com.yuchen.ishop.entity.Dictionary;
import com.yuchen.ishop.service.admin.goods.GoodsTypeService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class GoodsTypeServiceImpl implements GoodsTypeService {

    @Autowired
    private BaseDao dao;

    @Override
    public Dictionary insert(Dictionary t) {
        return dao.insert(t);
    }

    @Override
    public int update(Dictionary dictionary,boolean isIgnoreNull) {
        if(isIgnoreNull) return dao.updateIgnoreNull(dictionary);
        return dao.update(dictionary);
    }

    @Override
    public Dictionary getById(Long id) {
        return dao.fetch(Dictionary.class,id);
    }

    @Override
    public List find() {
        Condition c = Cnd.where("dicKey", "=", Gobals.SYS_GOODS_TYPE_KEY).asc("sort");
        return dao.query(Dictionary.class,c);
    }

    @Override
    public int delete(Long id) {
        return dao.delete(Dictionary.class,id);
    }

    @Override
    public void sortUp(Long id,Long sort) {
        Condition c = Cnd.where("sort", "<", sort).desc("sort");
        Dictionary dictionary1 = dao.fetch(Dictionary.class,id);//原
        Dictionary dictionary2 = dao.fetch(Dictionary.class,c); //找到前一个排序的dictionary
        dictionary1.setSort(dictionary2.getSort());
        dictionary2.setSort(sort);
        dao.update(dictionary1);
        dao.update(dictionary2);
    }

    @Override
    public void sortDown(Long id, Long sort) {
        Condition c = Cnd.where("sort", ">", sort).asc("sort");
        Dictionary dictionary1 = dao.fetch(Dictionary.class,id);//原
        Dictionary dictionary2 = dao.fetch(Dictionary.class,c); //找到前一个排序的dictionary
        dictionary1.setSort(dictionary2.getSort());
        dictionary2.setSort(sort);
        dao.update(dictionary1);
        dao.update(dictionary2);
    }

    @Override
    public Long getMaxSort() {
        String sql ="select case when max(sort) is null then 1  " +
                "else max(sort)+1 end sort " +
                "from t_dictionaries where dic_key='goods_type'";
        return (Long) dao.fn(sql,null);
    }
}
